<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Intent Recognition</title>

    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            background: repeating-linear-gradient(to top, #30cfd0 0%, #330867 100%);
            /*background: linear-gradient(217deg, rgba(255,0,0,.8), rgba(255,0,0,0) 70.71%),*/
            /*linear-gradient(127deg, rgba(0,255,0,.8), rgba(0,255,0,0) 70.71%),*/
            /*linear-gradient(336deg, rgba(0,0,255,.8), rgba(0,0,255,0) 70.71%);*/
            background-attachment: fixed;
            height: 760px;
            color: #ffffff;
            line-height: 1.8;
        }

        .main {
            max-width: 500px;
            margin: 30px auto;
            padding: 20px;
        }

        .log {
            background: rgba(255, 255, 255, 0.5);
            color: #333333;
            padding: 15px 25px;
            text-align: center;
            margin-bottom: 50px;
        }

        /*.inputs {*/
        /*    display: block;*/
        /*    width: 100%;*/
        /*    padding: 10px;*/
        /*    margin: 5px 20px;*/
        /*    border: 200px;*/
        /*}*/

        button {
            display: block;
            width: 20%;
            padding: 10px;
            margin: 20px auto;
            font-size: 15pt;
        }
        .voice {
            display: inline-block;
            margin: 10px 50px;
        }

        input {
            outline: none;
        }

        #body {
            background: rgba(255, 255, 255, 0.5);
            color: #333333;
            padding: 15px 25px;
            text-align: center;
            font-size: large;
            margin: 20px 100px;
        }
    </style>
</head>
<body>
<div id="body">
    <div style="text-align: justify">注：我们会将对您输入的文本进行成分分析，并猜测您在文本中表达的真实需求和目的。</div>
    <hr style="margin: 20px auto">
    <label for="content" style="display: block">请输入文本</label>
    <textarea name="content" id="content" class="inputs" cols="30" rows="5"
              style="font-family: Microsoft YaHei; margin: 5px 20px; width: 481px; height: 144px;"></textarea>
    <hr style="visibility: hidden">
    <button type="button" id="start" class="voice">语音输入</button>
    <button id="stop" class="voice">放弃输入</button>
    <button type="button" onclick="predict()">预 测</button>
    <button type="button" id="download">下载音频</button>
    <hr id="sep" style="display: none">
    <div id="result" style="color: #822739;margin-top: 5px; font-size: 18pt"></div>
</div>
</body>
<script src="../static/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    function predict() {
        var cont = $("#content").val()
        if (cont === "") {
            return
        }
        var data = {
            "content": cont
        }
        $.ajax({
            type: 'POST',
            url: '/predict_int',
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (res) {
                $("#sep").attr("style", "display: block; margin-top: 20px")
                $("#result").html("意图：" + res["intent"])
                delete res["intent"]
                for (var i in res) {
                    $("#result").append(
                        "\
                        <hr > \
                        <div style=\"color: #614DCE;margin-top: 5px; font-size: 16pt\">"
                        + res[i] + "：" + i + "</div> \
                        "
                    )
                }
            }
        })
    }
    var stt = document.getElementById("start")
    stt.onclick = function () {
        navigator.mediaDevices.getUserMedia({
            audio: true,
            video: false,
        }).then(stream => {
            var rcgn = new webkitSpeechRecognition();
            rcgn.continuous = true;
            rcgn.interimResults = true;
            rcgn.lang = 'cmn-Han-CN';
            console.log(MediaRecorder.isTypeSupported('audio/webm'))
            var mediaRecorder = new MediaRecorder(stream, {
                audioBitsPerSecond: 128000,
                mimeType: 'audio/webm'
            })
                console.log("start recording")
                mediaRecorder.start()
                rcgn.start()
            var stp = document.getElementById("stop")
            stp.onclick = function () {
                console.log("stop recording")
                if (mediaRecorder.state !== 'inactive') {
                    mediaRecorder.stop()
                }
                rcgn.abort()
                // console.log(stream.getAudioTracks())
                // stream.getAudioTracks()[0].stop()
                // console.log(stream.getAudioTracks())
            }
            rcgn.onresult = function (evt) {
                $("#content").html(evt["results"]['0']['0']['transcript'])
                if (mediaRecorder.state !== 'inactive') {
                    mediaRecorder.stop()
                }
            }
            mediaRecorder.ondataavailable = function (data) {
                // console.log(data.data)
                blob = new Blob([data.data], {'type': 'audio/mp3'})
                let file = new window.File([data.data], 'audio', {type: 'audio/mp3'})
                // console.log(file)
                let form = new FormData()
                form.append('wave_file', file)
                console.log('xml')
                var xml = new XMLHttpRequest()
                xml.open('POST', '/save')
                xml.send(form)
            }
            var dow = document.getElementById("download")
            dow.onclick = function () {
                console.log("Start downloading")
                $.ajax({
                    type: 'GET',
                    url: '/download',
                    success: function (data) {
                        console.log(data["filename"])
                        let a = document.createElement('a')
                        a.href = URL.createObjectURL(blob)
                        a.download = data["filename"]
                        a.click()
                        console.log(blob)
                    }
                })
            }
        }).catch(err => {
            console.log(err)

        })
    }
</script>
</html>